package com.googlecode.afdbaccess.web.common.login;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;

import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import com.googlecode.afdbaccess.cache.resultconversion.helpers.ResultSetConverterWithResult;

// TODO: Pull this up to some place where all tests can use it
class ResultFromConverterWithResultAnswer<T> implements Answer<T> {
    private Iterator<ResultSet> resultSetIterator;
    
    public ResultFromConverterWithResultAnswer(ResultSet resultSet) {
        ArrayList<ResultSet> resultSetList = new ArrayList<ResultSet>();
        resultSetList.add(resultSet);
        
        this.resultSetIterator = resultSetList.iterator();
    }
    
    public ResultFromConverterWithResultAnswer(Iterator<ResultSet> resultSetIterator) {
        this.resultSetIterator = resultSetIterator;
    }
    
    private ResultSet getNextResultSet() {
        return resultSetIterator.next();
    }
    
    @Override
    public T answer(InvocationOnMock invocation) throws Exception {
        Object[] args = invocation.getArguments();
        
        @SuppressWarnings("unchecked")
        Class<? extends ResultSetConverterWithResult<T>> converterClass = (Class<? extends ResultSetConverterWithResult<T>>)args[2];
        ResultSetConverterWithResult<T> converter = converterClass.newInstance();
        
        converter.convertResultSetToData(getNextResultSet());
        
        return converter.getResult();
    }
}
